import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { User, Permission } from '@/types'
import { hasPermission } from '@/utils/permission'

const TOKEN_KEY = 'student_system_token'
const USER_KEY = 'student_system_user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const user = ref<User | null>(null)

  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => user.value?.realName || user.value?.username || '')
  const userRole = computed(() => user.value?.role)

  /**
   * 设置用户信息
   */
  function setUser(userData: User, userToken: string) {
    user.value = userData
    token.value = userToken
    
    // 保存到本地存储
    localStorage.setItem(TOKEN_KEY, userToken)
    localStorage.setItem(USER_KEY, JSON.stringify(userData))
  }

  /**
   * 登出
   */
  function logout() {
    user.value = null
    token.value = ''
    
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_KEY)
  }

  /**
   * 从本地存储初始化用户信息
   */
  function initUserFromStorage() {
    const storedToken = localStorage.getItem(TOKEN_KEY)
    const storedUser = localStorage.getItem(USER_KEY)
    
    if (storedToken && storedUser) {
      try {
        token.value = storedToken
        user.value = JSON.parse(storedUser)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logout()
      }
    }
  }

  /**
   * 检查权限
   */
  function checkPermission(permission: Permission | Permission[]): boolean {
    return hasPermission(user.value, permission)
  }

  return {
    token,
    user,
    isLoggedIn,
    userName,
    userRole,
    setUser,
    logout,
    initUserFromStorage,
    checkPermission
  }
})

